﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QASampling.BusinessObject;
using QASampling.Util;
using QASampling.QAControl;
using System.Configuration;

namespace QASampling.UI
{
    public partial class frmQATable : BaseDialog
    {
        private string tableSource = string.Empty;
        public string TableSource
        {
            get { return tableSource; }
            set { tableSource = value; }
        }

        private string[] fieldName;
        public string[] FieldName
        {
            get { return fieldName; }
            set { fieldName = value; }
        }

        private string[] fieldValue;
        public string[] FieldValue
        {
            get { return fieldValue; }
            set { fieldValue = value; }
        }

        private string[] fieldBefore;
        public string[] FieldBefore
        {
            get { return fieldBefore; }
            set { fieldBefore = value; }
        }

        private string[] labelText;
        public string[] LabelText
        {
            get { return labelText; }
            set { labelText = value; }
        }

        private int[] fieldLength;
        public int[] FieldLength
        {
            get { return fieldLength; }
            set { fieldLength = value; }
        }

        private JenisCommand fieldCommand;
        public JenisCommand FieldCommand
        {
            get { return fieldCommand; }
            set { fieldCommand = value; }
        }

        private JenisField[] fieldType;
        public JenisField[] FieldType
        {
            get { return fieldType; }
            set { fieldType = value; }
        }

        private string[] dateFormat;
        public string[] DateFormat
        {
            get { return dateFormat; }
            set { dateFormat = value; }
        }

        private string tableNo = string.Empty;
        public string TableNo
        { 
            get { return tableNo; }
            set { tableNo = value; }
        }

        private int[] digits;
        public int[] Digits
        {
            get { return digits; }
            set { digits = value; }
        }

        public frmQATable()
        {
            InitializeComponent();
        }

        private void frmInsertTable_Load(object sender, EventArgs e)
        {
            try
            {
                int y = 0;
                int i = 0;

                for (i = 0; i < fieldName.Length; i++)
                {
                    y += 30;
                    var label = new System.Windows.Forms.Label();
                    label.AutoSize = true;
                    label.Location = new System.Drawing.Point(26, y);
                    label.Name = "label" + i;
                    label.Size = new System.Drawing.Size(41, 13);
                    label.Text = labelText[i];

                    y += 16;
                    var textbox = new QAControl.QATextbox();
                    if (fieldCommand != JenisCommand.Delete)
                    {
                        textbox.DateFormat = dateFormat[i];
                        textbox.FieldType = fieldType[i];
                        textbox.Digits = digits[i];
                    }
                    
                    textbox.Location = new System.Drawing.Point(26, y);
                    textbox.Name = "textbox" + i;
                    textbox.Size = new System.Drawing.Size(363, 21);
                    textbox.TabIndex = i;
                    textbox.MaxLength = fieldLength[i];
                    if (fieldValue != null)
                        textbox.Text = fieldValue[i];

                    if (fieldCommand == JenisCommand.Delete || fieldName[i].Equals(QAConstants.MUST_HAVE_FIELD))
                    {
                        label.Hide();
                        textbox.Hide();
                        y -= 46;
                    }

                    this.Controls.Add(label);
                    this.Controls.Add(textbox);
                }

                y += 30;
                this.lblQA.Location = new Point(26, y);
                this.lblQA.TabIndex = i;
                y += 16;
                this.cmbAlasanQA.Location = new Point(26, y);
                this.cmbAlasanQA.TabIndex = i + 1;
                cmbAlasanQA.DataSource = QAController.GetAlasanQA();
                cmbAlasanQA.SelectedIndex = 0;

                if (fieldCommand.Equals(JenisCommand.Insert))
                {
                    btnSimpan.Text = "Simpan";
                } 
                else if (fieldCommand.Equals(JenisCommand.Delete))
                {
                    btnSimpan.Text = "Hapus";
                }
                this.Height = y + 125;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSimpan_Click(object sender, EventArgs e)
        {
            try
            {
                string id = string.Empty;
                if (!this.ValidateChildren() || !GetValidation())
                    return;
                if (!CheckEmptyField())
                {
                    MessageBox.Show("Harap diisi minimal 1 Field", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                GetFieldValue();
                if (fieldCommand.Equals(JenisCommand.Insert) || fieldCommand.Equals(JenisCommand.Update))
                {
                    // if insert no need to get original value
                    fieldBefore = new string[0];

                    // preparing data to be inserted
                    ValidationUtil.ValidatingField(this);

                    // check is there field ID
                    if (fieldName.Contains(QAConstants.MUST_HAVE_FIELD) && fieldName.Length == fieldValue.Length)
                    {
                        int idx = fieldName.ToList().IndexOf(QAConstants.MUST_HAVE_FIELD);
                        id = fieldValue[idx];
                        // removing field ID when insert
                        List<string> lstTemp = new List<string>();
                        lstTemp = fieldName.ToList();
                        lstTemp.RemoveAt(idx);
                        fieldName = lstTemp.ToArray();

                        lstTemp = fieldValue.ToList();
                        lstTemp.RemoveAt(idx);
                        fieldValue = lstTemp.ToArray();
                    }                    
                }
                if (fieldCommand.Equals(JenisCommand.Insert))
                {
                    //added by Vincent 20130219 to upper case in table
                    for (int i = 0; i < fieldValue.Length; i++)
                    {
                        fieldValue[i] = fieldValue[i].ToUpper();
                    }
                    //-------------------------------------------------

                    QAController.TambahField(fieldName, fieldValue, tableSource, tableNo);
                }
                else if (fieldCommand.Equals(JenisCommand.Delete))
                {
                    QAController.HapusField(fieldName, fieldValue, tableSource);
                }
                else if (fieldCommand.Equals(JenisCommand.Update))
                {
                    //added by Vincent 20130219 to upper case in table
                    for (int i = 0; i < fieldValue.Length; i++)
                    {
                        fieldValue[i] = fieldValue[i].ToUpper();
                    }
                    //-------------------------------------------------

                    QAController.EditField(fieldName, fieldValue, tableSource, id);
                }

                // create change log
                QAChangeLog qa = new QAChangeLog();
                qa.FieldAction = fieldCommand.ToString();
                qa.FieldTable = tableSource;
                qa.FieldChanged = StringUtil.ConvertToString(fieldName);
                qa.FieldValue = StringUtil.ConvertToString(fieldValue);
                qa.FieldBefore = StringUtil.ConvertToString(fieldBefore);          
                qa.Comments = cmbAlasanQA.SelectedValue.ToString();                
                QAController.TambahQALog(qa);

                DialogResult = DialogResult.OK;

                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void GetFieldValue()
        {
            var ctl = from c in this.Controls.OfType<QATextbox>()
                      where ((QATextbox)c).Name.Contains("textbox")
                      orderby c.Name ascending
                      select c;

            StringBuilder sb = new StringBuilder();
            foreach (QATextbox tb in ctl)
            {
                sb.Append(tb.Text);
                sb.Append(";");
            }
            sb = sb.Remove(sb.Length - 1, 1);

            string[] ret = sb.ToString().Split(';');
            this.fieldValue = ret;
        }

        private bool GetValidation()
        {
            var ctl = from c in this.Controls.OfType<QATextbox>()
                      where ((QATextbox)c).Name.Contains("textbox")
                      orderby c.Name ascending
                      select c;

            bool valid = true;
            foreach (QATextbox tb in ctl)
            {
                valid = valid && string.IsNullOrEmpty(tb.ErrorMsg);
            }

            return valid;
        }

        private bool CheckEmptyField()
        {
            var ctl = from c in this.Controls.OfType<QATextbox>()
                      where ((QATextbox)c).Text != string.Empty
                      orderby c.Name ascending
                      select c;

            bool valid = true;
            if (ctl.Count() == 0)
            {
                valid = false;
            }

            return valid;
        }

        private void btnBatal_Click(object sender, EventArgs e)
        {
            Close();
        }

        /*private void txtFieldValue_Validating(object sender, CancelEventArgs e)
        {
            message = string.Empty;
            if (fieldType.Equals(JenisField.Datetime))
            {
                if (!ValidationUtil.IsValidDate(txtFieldValue.Text, dateFormat))
                {
                    txtFieldValue.BackColor = Color.Red;
                    message = "Masukkan penanggalan dengan benar " + dateFormat;
                }
            }
            else if (fieldType.Equals(JenisField.Currency))
            {
                if (!ValidationUtil.IsValidCurrency(txtFieldValue.Text, true))
                {
                    txtFieldValue.BackColor = Color.Red;
                    message = "Masukkan penulisan uang dengan benar";
                }
            }
        }

        private void txtFieldValue_TextChanged(object sender, EventArgs e)
        {
            txtFieldValue.BackColor = Color.LightGreen;
            tooltip.Hide(txtFieldValue);
        }

        private void txtFieldValue_MouseHover(object sender, EventArgs e)
        {
            tooltip.SetToolTip(txtFieldValue, message);
            tooltip.Show(message, txtFieldValue, 10, 15, 2000);
        }*/        
    }
}
